package org.outlook.apps.lunar;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LunarUtil {

	final static long[] lunarInfo = new long[] { 0x04bd8, 0x04ae0, 0x0a570,
			0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
			0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0,
			0x0ada2, 0x095b0, 0x14977, 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50,
			0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566,
			0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0,
			0x1c8d7, 0x0c950, 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4,
			0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, 0x06ca0, 0x0b550,
			0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950,
			0x06aa0, 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260,
			0x0f263, 0x0d950, 0x05b57, 0x056a0, 0x096d0, 0x04dd5, 0x04ad0,
			0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
			0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40,
			0x0af46, 0x0ab60, 0x09570, 0x04af5, 0x04970, 0x064b0, 0x074a3,
			0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960,
			0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0,
			0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9,
			0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0,
			0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65,
			0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0,
			0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, 0x0b5a0, 0x056d0, 0x055b2,
			0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0 };

	final static int[] solarMonth = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	final static String[] Animals = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
	final static String[] Gan = new String[] { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
	final static String[] Zhi = new String[] { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
	final static String chineseNumber[] = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };
	final static String[] nStr1 = new String[] { "日", "一", "二", "三", "四", "五", "六" };
	final static String[] solarTerm = new String[] { "小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至" };
	final static int[] sTermInfo = new int[] { 0,21208,42467,63836,85337,107014,128867,150921,173149,195551,218072,240693,263343,285989,308563,331033,353350,375494,397447,419210,440795,462224,483532,504758 };
	final static String[] nStr2 = new String[] { "初", "十", "廿", "卅", "　" };
	final static String[] monthName = new String[] { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };

	// 国历节日 *表示放假日
	final static String[] sFtv = new String[] {
		"0101*元旦",
		"0214 情人节",
		"0303 我生日",
		"0308 妇女节",
		"0312 植树节",
		"0315 消费者权益日",
		"0317 St. Patrick's",
		"0401 愚人节",
		"0501 劳动节",
		"0504 青年节",
		"0512 护士节",
		"0512 茵生日",
		"0601 儿童节",
		"0614 Flag Day",
		"0701 建党节 香港回归纪念",
		"0703 炎黄在线诞辰",
		"0718 托普诞辰",
		"0801 建军节",
		"0808 父亲节",
		"0909 毛泽东逝世纪念",
		"0910 教师节",
		"0928 孔子诞辰",
		"1001*国庆节",
		"1006 老人节",
		"1024 联合国日",
		"1111 Veteran's / Remembrance Day",
		"1112 孙中山诞辰纪念",
		"1220 澳门回归纪念",
		"1225 Christmas Day",
		"1226 毛泽东诞辰纪念"
	};

	// 农历节日 *表示放假日
	final static String[] lFtv = new String[] {
		"0101*春节",
		"0115 元宵节",
		"0505 端午节",
		"0707 七夕情人节",
		"0715 中元节",
		"0815 中秋节",
		"0909 重阳节",
		"1208 腊八节",
		"1224 小年",
		"0100*除夕"
	};

	// 某月的第几个星期几
	final static String[] wFtv = new String[] {
		"0131 Martin Luther King Day",
		"0231 President's Day",
		"0520 母亲节",
		"0530 Armed Forces Day",
		"0531 Victoria Day",
		"0716 合作节",
		"0730 被奴役国家周",
		"0811 Civic Holiday",
		"0911 Labor Holiday",
		"1021 Columbus Day",
		"1144 Thanksgiving"
	};
	private static final String FTV_REG_EXP = "(?m)^(\\d{2})(\\d{2})([\\s\\*])(.+)$";
	private static final Pattern FTV_REG_EXP_PATTERN = Pattern.compile(FTV_REG_EXP);
	private static final String WFTV_REG_EXP = "(?m)^(\\d{2})(\\d)(\\d)([\\s\\*])(.+)$";
	private static final Pattern WFTV_REG_EXP_PATTERN = Pattern.compile(WFTV_REG_EXP);
	private static final String LFTV_REG_EXP = "(?m)^(\\d{2})(.{2})([\\s\\*])(.+)$";
	private static final Pattern LFTV_REG_EXP_PATTERN = Pattern.compile(LFTV_REG_EXP);

	// ====== 传回农历 y年闰月的天数
	final static int leapDays(int y) {
		if (leapMonth(y) != 0) {
			if ((lunarInfo[y - 1900] & 0x10000) != 0)
				return 30;
			else
				return 29;
		} else
			return 0;
	}

	// ====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0
	final static int leapMonth(int y) {
		return (int) (lunarInfo[y - 1900] & 0xf);
	}

	// ====== 传回农历 y年m月的总天数
	final static int monthDays(int y, int m) {
		if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)
			return 29;
		else
			return 30;
	}

	// ==============================传回国历 y年某m+1月的天数
	final private static int solarDays(int y, int m) {
		if (m == 1)
			return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28);
		else
			return (solarMonth[m]);
	}

	// ===== 某年的第n个节气为几日(从0小寒起算)
	@SuppressWarnings("deprecation")
	final private static int sTerm(int y, int n) {
		Date offDate = new Date((long) (31556925974.7 * (y - 1900) + sTermInfo[n] * 60000) + Date.UTC(1900, 0, 6, 2, 5, 0));
		return (offDate.getDate());
	}

	// ====== 传回农历 y年的生肖
	final public static String animalsYear(int year) {
		return Animals[(year - 4) % 12];
	}

	// ====== 传入 月日的offset 传回干支, 0=甲子
	final private static String cyclicalm(int num) {
		return (Gan[num % 10] + Zhi[num % 12]);
	}

	// ====== 传入 offset 传回干支, 0=甲子
	final public static String cyclical(int num) {
//		num = num - 1900 + 36;
		return (cyclicalm(num));
	}

	// ============================== 传回月历物件 (y年,m+1月)
	public static LunarElement[] calendar(int y, int m) {
		int lY = 0, lM = 0, lD = 1, lX = 0, tmp1, tmp2;
		Lunar lDObj = null;
		boolean lL = false;
		int[] lDPOS = new int[3];
		int n = 0;
		int firstLM = 0;

		Calendar calendar = Calendar.getInstance();// Date sDObj = new Date(y,m,1);  //当月一日日期
		calendar.set(y, n, 1);

		int length = solarDays(y, m); // 国历当月天数
		int firstWeek = calendar.get(Calendar.DAY_OF_WEEK);// sDObj.getDay(); //国历当月1日星期几

		LunarElement[] elements = new LunarElement[length];
		for (int i = 0; i < length; i++) {

			if (lD > lX) {
				// sDObj = new Date(y,m,i+1); //当月一日日期
				// calendar.setTime(sDObj);
				calendar.set(y, m, i + 1);
				lDObj = new Lunar(calendar); // 农历
				lY = lDObj.year; // 农历年
				lM = lDObj.month; // 农历月
				lD = lDObj.day; // 农历日
				lL = lDObj.leap; // 农历是否闰月
				lX = lL ? leapDays(lY) : monthDays(lY, lM); // 农历当月最後一天

				if (n == 0)
					firstLM = lM;
				lDPOS[n++] = i - lD + 1;
			}

			// sYear,sMonth,sDay,week,
			// lYear,lMonth,lDay,isLeap,
			// cYear,cMonth,cDay
			elements[i] = new LunarElement(y, m + 1, i + 1,
					nStr1[(i + firstWeek) % 7], lY, lM, lD++, lL,
					cyclical(lDObj.yearCyl), cyclical(lDObj.monCyl),
					cyclical(lDObj.dayCyl++));

			if ((i + firstWeek) % 7 == 0)
				elements[i].setColor("red"); // 周日颜色
			if ((i + firstWeek) % 14 == 13)
				elements[i].setColor("red"); // 周休二日颜色
		}

		// 节气
		tmp1 = sTerm(y, m * 2) - 1;
		tmp2 = sTerm(y, m * 2 + 1) - 1;
		elements[tmp1].setSolarTerms(solarTerm[m * 2]);
		elements[tmp2].setSolarTerms(solarTerm[m * 2 + 1]);
		if (m == 3)
			elements[tmp1].setColor("red"); // 清明颜色

		// 国历节日
		Matcher matcher;
		for (String i : sFtv)
			if (i.matches(FTV_REG_EXP)) {
				matcher = FTV_REG_EXP_PATTERN.matcher(i);
				matcher.find();
				if (Integer.parseInt(matcher.group(1)) == m + 1) {
					final int j = Integer.parseInt(matcher.group(2)) - 1;
					elements[j].setSolarFestival((elements[j].getSolarFestival()==null?"":elements[j].getSolarFestival()) + matcher.group(4) + ' ');
					if (matcher.group(3).equals("*"))
						elements[j].setColor("red");
				}
			}

		// 月周节日
		for (String i : wFtv)
			if (i.matches(WFTV_REG_EXP)) {
				matcher = WFTV_REG_EXP_PATTERN.matcher(i);
				matcher.find();
				if (Integer.parseInt(matcher.group(1)) == m + 1) {
					tmp1 = Integer.parseInt(matcher.group(2));
					tmp2 = Integer.parseInt(matcher.group(3));
					final int j = ((firstWeek > tmp2) ? 7 : 0) + 7 * (tmp1 - 1) + tmp2 - firstWeek;
					elements[j].setSolarFestival((elements[j].getSolarFestival()==null?"":elements[j].getSolarFestival()) + matcher.group(5) + ' ');
				}
			}

		// 农历节日
		for (String i : lFtv)
			if(i.matches(LFTV_REG_EXP)) {
				matcher = LFTV_REG_EXP_PATTERN.matcher(i);
				matcher.find();
				tmp1 = Integer.parseInt(matcher.group(1)) - firstLM;
				if (tmp1 == -11)
					tmp1 = 1;
				if (tmp1 >= 0 && tmp1 < n) {
					tmp2 = lDPOS[tmp1] + Integer.parseInt(matcher.group(2)) - 1;
					if (tmp2 >= 0 && tmp2 < length) {
						elements[tmp2].setLunarFestival((elements[tmp2].getLunarFestival()==null?"":elements[tmp2].getLunarFestival()) + matcher.group(4) + ' ');
						if (matcher.group(3).equals("*"))
							elements[tmp2].setColor("red");
					}
				}
			}

		// 黑色星期五
		if ((firstWeek + 12) % 7 == 5)
			elements[12].setSolarFestival(elements[12].getSolarFestival() + "黑色星期五 ");

		// 今日
		calendar = Calendar.getInstance();
		if (y == calendar.get(Calendar.YEAR) && m == calendar.get(Calendar.MONTH))
			elements[calendar.get(Calendar.DAY_OF_MONTH) - 1].setToday(true);

		return elements;
	}

	public static String getChinaDayString(int day) {
		int n = day % 10 == 0 ? 9 : day % 10 - 1;
		if (day > 30)
			return "";
		if (day == 10)
			return "初十";
		else
			return nStr2[day / 10] + chineseNumber[n];
	}

	public static String getEllipticalExpression(String str) {
		if(str.length()>5){
			return str.substring(0, 5)+"...";
		}
		return str;
	}

	public static String getLunarTooltip(LunarElement el) {
		StringBuffer sb = new StringBuffer("<html><TABLE WIDTH=100% BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD ALIGN='right'><FONT STYLE='font-size:9pt;'>");
		sb.append("<font color='violet'>农历 ").append(el.getlYear()).append(" 年 ").append(el.getlMonth()).append(" 月 ").append(getChinaDayString(el.getlDay()));
		sb.append("</font><br><font color='yellow'>").append(el.getcYear()).append(" 年 ").append(el.getcMonth()).append(" 月 ").append(el.getcDay()).append(" 日 ").append("</font></FONT></TD></TR>");
		if(el.isSpecialDay()){
			sb.append("<TR><TD><FONT COLOR='#000066' STYLE='font-size:9pt;'>").append(el.getLunarFestival()==null?"":el.getLunarFestival()+' ').append(el.getSolarFestival()==null?"":el.getSolarFestival()+' ').append(el.getSolarTerms()==null?"":el.getSolarTerms()+' ').append("</FONT></TD></TR>");
		}
		sb.append("</TABLE></html>");
		return sb.toString();
	}

}
